<template>
  <div class="calculator-container">
    <!-- 顶部导航区域 -->
    <div class="top-navigation">
      <div class="nav-content container">
        <div class="nav-left">
          <h1 class="main-title">
            <span class="title-icon">🎯</span>
            REWARD 计算器
          </h1>
          <p class="subtitle">智能奖励计算，助力学习进步</p>
        </div>
        <div class="nav-right">
          <div class="nav-actions">
            <ThemeSwitcher class="theme-switcher-nav" />
            <el-button-group class="action-buttons">
              <el-button
                type="info"
                :icon="Download"
                @click="downloadRules"
                class="nav-btn btn-primary"
                size="large"
              >
                规则文档
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：表单区域 -->
      <div class="form-section">
        <el-card shadow="hover" class="form-card card">
          <template #header>
            <div class="card-header">
              <div class="header-icon">📝</div>
              <div class="header-content">
                <h3>成绩录入</h3>
                <p>请输入各科目成绩和当前排名</p>
              </div>
            </div>
          </template>

          <CalculatorForm
            :subjects="subjects"
            :loading="loading"
            :is-mobile="isMobile"
            @form-submit="handleCalculate"
            @clear="handleClearForm"
            ref="formRef"
          />
        </el-card>

        <!-- 分数趋势图表组件 -->
        <transition name="slide-fade" mode="out-in">
          <ScoreTrendChart
              :history="history"
              :subjects="subjects"
              :is-mobile="isMobile"
              @subject-change="handleSubjectChange"
          />
        </transition>

        <!-- 二维码 -->
        <transition name="slide-fade" mode="out-in">
          <QrDownload />
        </transition>
      </div>

      <!-- 右侧：结果展示区域 -->
      <div class="result-section">
        <!-- 结果卡片 -->
        <transition name="slide-fade" mode="out-in">
          <ResultDisplay
            v-if="result"
            :result="result"
            :is-mobile="isMobile"
            class="result-card card"
          />
        </transition>

        <!-- 历史记录卡片 -->
        <transition name="slide-fade" mode="out-in">
          <HistoryManager
            v-if="history.length"
            :history="history"
            :subjects="subjects"
            :is-mobile="isMobile"
            @load-history="handleLoadHistory"
            @delete-record="handleDeleteRecord"
            @batch-delete="handleBatchDelete"
            @download-pdf="handleDownloadPdf"
            class="history-card card"
          />
        </transition>
      </div>
    </div>

    <!-- 加载遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-content">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p>正在计算奖励...</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { Download, Loading } from '@element-plus/icons-vue'
import CalculatorForm from './calculator/CalculatorForm.vue'
import ResultDisplay from './calculator/ResultDisplay.vue'
import HistoryManager from './calculator/HistoryManager.vue'
import { useCalculator } from '@/composables/useCalculator'
import { useResponsive } from '@/composables/useResponsive'
import QrDownload from "@/components/calculator/QrDownload.vue";
import ScoreTrendChart from "@/components/calculator/ScoreTrendChart.vue";
import ThemeSwitcher from './ThemeSwitcher.vue'

export default {
  name: 'RewardCalculator',
  components: {
    ScoreTrendChart,
    QrDownload,
    Loading,
    CalculatorForm,
    ResultDisplay,
    HistoryManager,
    ThemeSwitcher
  },
  setup() {
    const {
      subjects,
      history,
      result,
      loading,
      loadSubjects,
      loadDataHistory,
      calculate,
      removeHistory,
      batchRemoveHistory,
      downloadPdf
    } = useCalculator()

    const { isMobile } = useResponsive()

    return {
      subjects,
      history,
      result,
      loading,
      isMobile,
      loadSubjects,
      loadDataHistory,
      calculate,
      removeHistory,
      batchRemoveHistory,
      downloadPdf,
      Download,
      Loading
    }
  },
  methods: {
    handleSubjectChange(subject) {
      // 可以在这里处理科目切换事件
      console.log('科目切换:', subject)
    },
    // 处理计算提交
    async handleCalculate(formData) {
      if (formData?.isTrusted) {
        console.warn('⚠️ 收到了事件对象，不是表单数据')
        return
      }
      await this.calculate(formData)
    },

    // 处理清空表单
    handleClearForm() {
      this.$confirm('确定要清空所有输入吗？', '清空确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'clear-confirm-dialog'
      }).then(() => {
        this.$refs.formRef?.clearForm()
        ElMessage({
          type: 'success',
          message: '表单已清空',
          duration: 2000
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消清空',
          duration: 2000
        })
      })
    },

    // 下载规则
    downloadRules() {
      const link = document.createElement('a')
      link.href = './rule.pdf'
      link.download = '奖励计算规则.pdf'
      link.click()
      ElMessage.success('规则文档下载中...')
    },

    // 处理加载历史记录
    handleLoadHistory(row) {
      this.$refs.formRef?.loadFormData(row.studentDto)
      this.result = row
    },

    // 处理删除记录
    async handleDeleteRecord(id) {
      this.$confirm('确定删除该记录吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'delete-confirm-dialog',
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            setTimeout(async () => {
              await this.removeHistory(id)
              done()
            }, 500)
          } else {
            done()
          }
        }
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
          duration: 2000
        })
      })
    },

    // 处理批量删除
    async handleBatchDelete(selectedRecords) {
      this.$confirm(
        `确定删除选中的 ${selectedRecords.length} 条记录吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'delete-confirm-dialog',
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '删除中...'
              setTimeout(async () => {
                await this.batchRemoveHistory(selectedRecords)
                done()
              }, 500)
            } else {
              done()
            }
          }
        }
      ).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
          duration: 2000
        })
      })
    },

    // 处理下载PDF
    handleDownloadPdf(id) {
      this.downloadPdf(id)
    }
  },
  async created() {
    await this.loadSubjects()
    await this.loadDataHistory()
  }
}
</script>

<style scoped>
/* 主容器 - 组件特定样式 */
.calculator-container {
  min-height: 100vh;
  background: var(--gradient-page);
  position: relative;
  overflow-x: hidden;
}

/* 顶部导航 - 组件特定样式 */
.top-navigation {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: var(--spacing-lg) 0;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: var(--shadow-light);
}

.nav-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: var(--spacing-lg);
}

.nav-left {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.main-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin: 0;
  font-size: var(--font-size-3xl);
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1.2;
}

.title-icon {
  font-size: var(--font-size-2xl);
}

.subtitle {
  margin: 0;
  color: var(--text-light);
  font-size: var(--font-size-base);
  font-weight: 400;
}

.nav-right {
  display: flex;
  align-items: center;
}

.nav-actions {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.theme-switcher-nav {
  transform: scale(0.9);
}

.action-buttons {
  display: flex;
  gap: var(--spacing-sm);
}

.nav-btn {
  border-radius: var(--border-radius-small);
  font-weight: 500;
  transition: var(--transition-base);
}

.nav-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-medium);
}

/* 主要内容区域 - 组件特定布局 */
.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: var(--spacing-xl) var(--spacing-lg);
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-xl);
  min-height: calc(100vh - 120px);
}

/* 表单区域 - 组件特定布局 */
.form-section {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

/* 卡片样式由全局 .card 提供，这里仅保留组件特定结构样式 */

/* 卡片头部样式由全局 components.css 提供 */

/* 头部样式由全局 components.css 提供 */

/* 结果区域 - 组件特定布局 */
.result-section {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

/* 结果和历史卡片样式由全局 .card 提供 */

/* 动画效果 - 组件特定的过渡动画 */
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: var(--transition-base);
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 加载遮罩 - 组件特定的加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  background: white;
  padding: var(--spacing-xl);
  border-radius: var(--border-radius);
  box-shadow: var(--shadow-heavy);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-md);
}

.loading-icon {
  font-size: var(--font-size-3xl);
  color: var(--primary-color);
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 - 组件特定的响应式规则 */
@media screen and (max-width: 1200px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: var(--spacing-lg);
  }
  
  .result-section {
    order: -1;
  }
  
  .nav-content {
    padding: 0 var(--spacing-lg);
  }
  
  .main-title {
    font-size: var(--font-size-2xl);
  }
  
  .subtitle {
    font-size: var(--font-size-base);
  }
}

@media screen and (max-width: 768px) {
  .calculator-container {
    min-height: 100vh;
  }
  
  .top-navigation {
    padding: var(--spacing-md) 0;
  }
  
  .nav-content {
    flex-direction: column;
    gap: var(--spacing-md);
    text-align: center;
    padding: 0 var(--spacing-md);
  }
  
  .nav-left {
    order: 1;
  }
  
  .nav-right {
    order: 2;
  }
  
  .main-title {
    font-size: var(--font-size-xl);
    margin-bottom: var(--spacing-xs);
  }
  
  .subtitle {
    font-size: var(--font-size-sm);
    margin-bottom: var(--spacing-sm);
  }
  
  .nav-actions {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-sm);
    align-items: center;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: center;
  }
  
  .nav-btn {
    flex: 1;
    max-width: 200px;
  }
  
  .main-content {
    padding: var(--spacing-md);
    gap: var(--spacing-md);
    grid-template-columns: 1fr;
  }
  
  .form-section {
    order: 2;
  }
  
  .result-section {
    order: 1;
  }
  
  .card-header {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-sm);
    padding: var(--spacing-md) 0;
  }
  
  .header-icon {
    width: 40px;
    height: 40px;
    font-size: var(--font-size-xl);
  }
  
  .header-content h3 {
    font-size: var(--font-size-lg);
  }
  
  .header-content p {
    font-size: var(--font-size-sm);
  }
}

@media screen and (max-width: 480px) {
  .calculator-container {
    background: var(--gradient-page);
    min-height: 100vh;
  }
  
  .top-navigation {
    padding: var(--spacing-sm) 0;
  }
  
  .nav-content {
    padding: 0 var(--spacing-sm);
    gap: var(--spacing-sm);
  }
  
  .main-title {
    font-size: var(--font-size-lg);
    line-height: 1.2;
  }
  
  .subtitle {
    font-size: var(--font-size-xs);
    line-height: 1.3;
  }
  
  .nav-actions {
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: var(--spacing-xs);
    width: 100%;
  }
  
  .nav-btn {
    max-width: none;
    width: 100%;
    font-size: var(--font-size-sm);
    padding: var(--spacing-sm) var(--spacing-md);
  }
  
  .main-content {
    padding: var(--spacing-sm);
    gap: var(--spacing-sm);
  }
  
  .card-header {
    padding: var(--spacing-sm) 0;
    gap: var(--spacing-xs);
  }
  
  .header-icon {
    width: 36px;
    height: 36px;
    font-size: var(--font-size-lg);
  }
  
  .header-content h3 {
    font-size: var(--font-size-base);
    margin-bottom: var(--spacing-xs);
  }
  
  .header-content p {
    font-size: var(--font-size-xs);
  }
  
  /* 移动端特殊优化 */
  .form-card,
  .result-card,
  .history-card {
    margin-bottom: var(--spacing-sm);
    border-radius: var(--border-radius-small);
  }
  
  .loading-content {
    padding: var(--spacing-lg);
    margin: var(--spacing-md);
  }
  
  .loading-icon {
    font-size: var(--font-size-2xl);
  }
}
</style>